//
//  SchoolNewsViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/22.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import XLPagerTabStrip
import SwiftyJSON

@objc protocol SchoolNewsDelegate {
    @objc optional func changeScrollHeight(height:CGFloat) //改变滑动高度
    @objc optional func updateTitle() //刷新标题
}

class SchoolNewsViewController: KMViewController,IndicatorInfoProvider {
    
    weak var delegate : SchoolNewsDelegate?
    
    fileprivate let cellId = "questionCell"
    fileprivate let cellId2 = "cardCell"
    
    fileprivate var schoolId = "" //学堂id
    fileprivate var type = "" //类型
    
    var dataArray = [QuestionModel]()
    var dataSource = [CardModel]()
    
    var itemInfo:IndicatorInfo = ""
    
    var urlString  = ""
    
    var page = 1
    
    fileprivate var tableView : UITableView!
    
    init(schoolId:String?,type:String?) {
        super.init(nibName: nil, bundle: nil)
        
        self.schoolId = schoolId ?? ""
        self.type = type ?? ""
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(QuestionCell.self, forCellReuseIdentifier: cellId)
        tableView.register(SchoolCardCell.self, forCellReuseIdentifier: cellId2)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        KMTool.setRefresh(with: tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getData()
            
        }) {[weak self] in
            
            self?.getData()
        }
        
        self.tableView.mj_header.beginRefreshing()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: 获取数据
    fileprivate func getData() {
        
        self.delegate?.updateTitle!()
        
        KMTool.requestGetData(URLString: url_school, parameters: ["id":self.schoolId,"type":self.type,"p":"\(self.page)"], success: { (data) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            let json = JSON.init(data)
            
            if let array = json.arrayObject as? [[String:Any]] {
                
                if self.page == 1 {
                    self.dataArray.removeAll()
                    self.dataSource.removeAll()
                }
                
                if self.type == "3" {
                    
                    for item in array {
                        let model = CardModel.setModel(with: item)
                        self.dataSource.append(model)
                    }
                    
                    
                }else{
                    
                    for item in array {
                        let model = QuestionModel.setModel(with: item)
                        self.dataArray.append(model)
                    }
                    
                }
                
                self.page += 1
            }
            
            self.tableView.reloadData()
            
        }) {
            
            self.tableView.mj_footer.endRefreshing()
            self.tableView.mj_header.endRefreshing()
        }
    }
    

    func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
        
        return itemInfo
        
    }
    
    //MARK: 免费申请
    @objc fileprivate func freeApplicationAction(sender:UIButton) {
        
        var urlString = ""
        
        let model = dataSource[sender.tag]
        if model.app_apply_access != "" {
            urlString = model.app_apply_access!
        }else if model.m_apply_access != "" {
            urlString = model.m_apply_access!
        }else if model.apply_access != "" {
            urlString  = model.apply_access!
        }
        
        if urlString == "" {
            return
        }
        
        let webDetailsVC = WebDetailsViewController.init(urlString: urlString)
        self.navigationController?.pushViewController(webDetailsVC, animated: true)
    }

}

extension SchoolNewsViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if self.type == "3" {
            return dataSource.count
        }else{
            return dataArray.count
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.type == "3" {
            let cell = tableView.dequeueReusableCell(withIdentifier: cellId2, for: indexPath) as? SchoolCardCell
            cell?.model = dataSource[indexPath.row]
            cell?.requestBtn.tag = indexPath.row
            cell?.requestBtn.addTarget(self, action: #selector(freeApplicationAction(sender:)), for: .touchUpInside)
            return cell!
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? QuestionCell
            cell?.model = dataArray[indexPath.row]
            return cell!
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if self.type == "3" {
            return RATIO_H(maxNum: 100)
        }else{
            return RATIO_H(maxNum: 120)
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if self.type == "3" {
            
            let model = dataSource[indexPath.row]
            let url = webUrl + "/mobile/details/i" + model.id!
            let webVC = WebViewController.init(urlString: url, title: self.itemInfo.title, shareImage: kmHttps + model.image!, shareText: model.favorable, shareTitle: model.credit_name)
            self.navigationController?.pushViewController(webVC, animated: true)
            
        }else{
            
            let model = dataArray[indexPath.row]
            let url = "https://www.kameng98.com/posts/" + model.id!
            let webVC = WebViewController.init(urlString: url, title: self.itemInfo.title, shareImage: kmHttps + "/data/upload/" + model.thumb!, shareText: model.posts_excerpt, shareTitle: model.posts_title)
            webVC.removeElements = ["mblocks","crumbs mblock","mfooter mblock footer1"]
            webVC.removeIds = ["xiong_div"]
            self.navigationController?.pushViewController(webVC, animated: true)
            
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.delegate?.changeScrollHeight!(height: scrollView.contentOffset.y)
    }
    
}
